package com.agh.portal.domain;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = { "findReplysByPost", "findReplysByStudent" })
public class Reply {

    @Size(max = 5000)
    @NotEmpty
    private String content;

    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "M-")
    private Date replyDate;

    @NotNull
    @ManyToOne
    private Post post;

    @NotNull
    @ManyToOne
    private Student student;

	public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }    
	
    public static List<Reply> findAllReplys() {
        return entityManager().createQuery("SELECT o FROM Reply o ORDER BY o.replyDate desc", Reply.class).getResultList();
    }
    
    
    public static List<Reply> findReplyEntries(int firstResult, int maxResults) {
        return entityManager().createQuery("SELECT o FROM Reply o ORDER BY o.replyDate desc", Reply.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }
    
    public static TypedQuery<Reply> findLatestReplysByStudent(Student student, Integer maxResults) {
        if (student == null) throw new IllegalArgumentException("The student argument is required");
        EntityManager em = Reply.entityManager();
        TypedQuery<Reply> q = em.createQuery("SELECT o FROM Reply AS o WHERE o.student = :student ORDER BY o.replyDate desc", Reply.class);
        q.setParameter("student", student);
        if(maxResults != null){
        	q.setMaxResults(maxResults);
        }
        return q;
    }
   
}
